<?php

namespace App\Http\Controllers\Admin;

use App\AppChannel;
use App\BlackAccessLog;
use App\Http\Controllers\Controller;
use App\ReferLog;
use App\UserApp;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Storage;

class IndexController extends Controller
{
    public function index()
    {
        $admin    = session('admin');
        $menuList = $admin->getMenus();
        return view('admin.index', ['menu' => $menuList]);
    }

    /**
     * 统计修改
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function console()
    {
        // 统计数据
        $model = new BlackAccessLog();
        $uid = session("admin")->getUid();
        if (!session('admin')->hasSuperRole()) {
            $appIds = UserApp::where("user_id", $uid)->pluck("id");
            $model = $model->whereIn("app_id", $appIds);
        }

        // 优化显示
        $redisCacheKey = "summary: " . $uid;
        $summary = Redis::get($redisCacheKey);
        if (empty($summary)) {

            // 今日命中总次数
            $todayCount = $model->where("access_date", date("Y-m-d"))->count();


            // 本周命中总次数
            $start = Carbon::now()->startOfWeek()->toDateString();
            $end = Carbon::now()->endOfWeek()->toDateString();
            $weekModel = new BlackAccessLog();
            if (!session('admin')->hasSuperRole()) {
                $uid = session("admin")->getUid();
                $appIds = UserApp::where("user_id", $uid)->pluck("id");
                $weekModel = $weekModel->whereIn("app_id", $appIds);
            }
            $weekCount = $weekModel->where("access_date", '>=', $start)
                ->where("access_date", "<=", $end)
                ->count();

            // 本月
            $start = Carbon::now()->startOfMonth()->toDateString();
            $end = Carbon::now()->endOfMonth()->toDateString();
            $monthModel = new BlackAccessLog();
            if (!session('admin')->hasSuperRole()) {
                $uid = session("admin")->getUid();
                $appIds = UserApp::where("user_id", $uid)->pluck("id");
                $monthModel = $monthModel->whereIn("app_id", $appIds);
            }
            $monthCount = $monthModel->where("access_date", '>=', $start)
                ->where("access_date", "<=", $end)
                ->count();


            $summaryArr["todayCount"] = $todayCount;
            $summaryArr["weekCount"] = $weekCount;
            $summaryArr["monthCount"] = $monthCount;

            Redis::setex($redisCacheKey, 3600, json_encode($summaryArr));
        } else {
            $summary = json_decode($summary, true);
            $todayCount = $summary["todayCount"];
            $weekCount = $summary["weekCount"];
            $monthCount = $summary["monthCount"];
        }


        // 访问前 20
        $uid = session("admin")->getUid();
        $redisCacheKey = "result: " . $uid;
        $result = Redis::get($redisCacheKey);
        if (empty($result)) {
            $referLogModel = new ReferLog();
            $referLogModel = $referLogModel->select(DB::raw("count(1) as total, url, type, channel_id, channel_name, app_name"));
            if (!session('admin')->hasSuperRole()) {
                $appIds = UserApp::where("user_id", $uid)->pluck("id");
                $referLogModel = $referLogModel->whereIn("app_id", $appIds);
            }

            $result = $referLogModel->where("channel_id", ">", 0)->groupBy("channel_id", "url")->orderBy("total", "desc")->take(10)->get();
            $result = !empty($result) ? $result->toArray() : [];

            if (!empty($result)) {
                foreach ($result as &$item) {
                    $shortWord = AppChannel::where("id", $item['channel_id'])->value("short_url_word");
                    $item['channel_url'] = '';
                    if (!empty($shortWord)) {
                        $item['channel_url'] = "https://lhxq.top/" . $shortWord;
                    }
                }
            }
            Redis::setex($redisCacheKey, 3600, json_encode($result));
        } else {
            $result = json_decode($result, true);
        }

        return view('admin.console', compact("todayCount", "weekCount", "monthCount", 'result'));
    }

    /**
     * @Desc: 后台图片上传
     * @Author: woann <304550409@qq.com>
     * @param Request $request
     * @return mixed
     */
    public function upload(Request $request)
    {
        $file = $request->file('image');
        $path = $request->input('path') . '/';
        if ($file) {
            if ($file->isValid()) {
                $size = $file->getSize();
                if ($size > 5000000) {
                    return $this->json(500, '图片不能大于5M！');
                }
                // 获取文件相关信息
                $ext = $file->getClientOriginalExtension(); // 扩展名
                if (!in_array($ext, ['png', 'jpg', 'gif', 'jpeg', 'pem'])) {
                    return $this->json(500, '文件类型不正确！');
                }
                $realPath = $file->getRealPath(); //临时文件的绝对路径
                // 上传文件
                $filename = $path . date('Ymd') . '/' . uniqid() . '.' . $ext;
                // 使用我们新建的uploads本地存储空间（目录）
                $bool = Storage::disk('admin')->put($filename, file_get_contents($realPath));
                if ($bool) {
                    return $this->json(200, '上传成功', ['filename' => '/uploads/' . $filename]);
                } else {
                    return $this->json(500, '上传失败！');
                }
            } else {
                return $this->json(500, '文件类型不正确！');
            }
        } else {
            return $this->json(500, '上传失败！');
        }
    }

    /**
     * @Desc: 富文本上传图片
     * @Author: woann <304550409@qq.com>
     * @param Request $request
     */
    public function wangeditorUpload(Request $request)
    {
        $file = $request->file('wangEditorH5File');
        if ($file) {
            if ($file->isValid()) {
                // 获取文件相关信息
                $ext      = $file->getClientOriginalExtension(); // 扩展名
                $realPath = $file->getRealPath(); //临时文件的绝对路径
                // 上传文件
                $filename = date('Ymd') . '/' . uniqid() . '.' . $ext;
                // 使用我们新建的uploads本地存储空间（目录）
                $bool = Storage::disk('admin')->put('/wangeditor/' . $filename, file_get_contents($realPath));
                if ($bool) {
                    echo asset('/uploads/wangeditor/' . $filename);
                } else {
                    echo 'error|上传失败';
                }
            } else {
                echo 'error|上传失败';
            }
        } else {
            echo 'error|图片类型不正确';
        }
    }

    /**
     * @Desc: 无权限界面
     * @Author: woann <304550409@qq.com>
     * @return \Illuminate\View\View
     */
    public function noPermission()
    {
        return view('base.403');
    }
}
